﻿#include "mainwindowimpl.h"
#include "ctkPluginContext.h"
#include "mainwindow.h"
#include <service/event/ctkEventConstants.h>
#include <service/event/ctkEventAdmin.h>
#include "PluginInterfaces.h"

MainWindowImpl::MainWindowImpl(ctkPluginContext *context)
    : m_context(context)
    , m_window(new MainWindow(context))
{
    ctkDictionary dic;
    dic.insert(ctkEventConstants::EVENT_TOPIC, TOPIC_HELLOWORD);
    context->registerService<ctkEventHandler>(this, dic);
}

MainWindowImpl::~MainWindowImpl()
{
    if(m_window != nullptr)
    {
        m_window->deleteLater();
    }
}

void MainWindowImpl::quitApp()
{
    if(m_window != nullptr)
        m_window->quitApp();
}

void MainWindowImpl::startAppWithArgs(const QStringList& fileList)
{
    if(m_window != nullptr)
        m_window->startAppWithArgs(fileList);
}

QQuickView* MainWindowImpl::getQuickView()
{
    if(m_window != nullptr)
        return m_window->getQuickView();

    return nullptr;
}

void MainWindowImpl::TestInterface()
{
	if(m_window != nullptr)
    {
        m_window->TestInterface();
    }
}

void MainWindowImpl::postCtkEvent(const QString event, const QVariant data, const QVariant extentionData)
{
    ctkEventAdmin *eventAdmin = getEventAdmin();
    if(eventAdmin != nullptr){
        ctkDictionary dic;
        dic.insert(PROPERTY_EVENT, event);
        dic.insert(PROPERTY_DATA, data);
        dic.insert(PROPERTY_EXTENTION, extentionData);
        eventAdmin->postEvent(ctkEvent(TOPIC_MAINWINDOW, dic));
    }
}

ctkEventAdmin* MainWindowImpl::getEventAdmin()
{
    ctkServiceReference ref;
    ctkEventAdmin *eventAdmin = nullptr;

    try {
        ref = m_context->getServiceReference<ctkEventAdmin>();
    }  catch (const ctkServiceException& e) {
        qCritical() << e.printStackTrace();
    } catch (...) {
        qCritical() << "Unknown exception.";
    }

    if (ref) {
        eventAdmin = m_context->getService<ctkEventAdmin>(ref);
        m_context->ungetService(ref);
    } else {
        qCritical() << "Get ctkEventAdmin error.";
    }

    return eventAdmin;
}

void MainWindowImpl::handleEvent(const ctkEvent &event)
{
    try {
    }
    catch (const ctkRuntimeException &e) {
        qWarning() << e.printStackTrace();
    } catch (...) {
        qWarning() << "Unknown exception.";
    }
}
